#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

namespace ThreadModule
{
    static int number = 1;
    using func_t = std::function<void(std::string name)>;
    enum TSTATUS
    {
        NEW,
        RUNNING,
        STOP
    };

    class Thread
    {
    private:
        static void *routine(void *args) // 静态成员函数没有this指针
        {
            Thread *t = static_cast<Thread*>(args);
            t->_status = TSTATUS::RUNNING;
            t->_func(t->Name());//静态成员函数没有this指针，不能直接使用成员变量
            return nullptr;
        }

        void EnableDetach()
        {
            _joinable = false;
        }
    public:
        Thread(func_t func)
            : _func(func), _status(TSTATUS::NEW), _joinable(true)
        {
            _name = "thread-" + std::to_string(number++);
            _pid = getpid();
        }

        bool Start()
        {
            if (_status != TSTATUS::RUNNING)
            {
                int n = pthread_create(&_tid, nullptr, routine, this);
                if (n != 0)
                {
                    return false;
                }
                return true;
            }
            return false;
        }

        bool Stop()
        {
            if (_status == TSTATUS::RUNNING)
            {
                int n = pthread_cancel(_tid);
                if (n != 0)
                {
                    return false;
                }
                _status = TSTATUS::STOP;
                return true;
            }
            return false;
        }

        bool Join()
        {
            if (_joinable)
            {
                int n = pthread_join(_tid, nullptr);
                if (n != 0)
                {
                    return false;
                }
                _status = TSTATUS::STOP;
                return true;
            }
            return false;
        }
        
        bool isJoinable()
        {
            return _joinable;
        }

        bool Detach()
        {
            EnableDetach();
            int n = pthread_detach(_tid);
            return n == 0 ? true : false;
        }

        std::string Name()
        {
            return _name;
        }

        ~Thread()
        {}

    private:
        std::string _name;
        pthread_t _tid;
        func_t _func;
        TSTATUS _status;
        pid_t _pid;
        bool _joinable;
    };
}